<template>
  <div class="process-trend-chart">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { getChartThemeOptions, watchThemeChange } from '@/utils/chartTheme'
import { formatBytes } from '@/utils/format'

const props = defineProps({
  processNames: {
    type: Array,
    default: () => []
  },
  testCases: {
    type: Array,
    default: () => []
  },
  metric: {
    type: Array,
    default: () => ['rss']
  },
  loading: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: '400px'
  },
  processData: {
    type: Array,
    default: () => []
  }
})

const chartRef = ref(null)
const themeObserver = ref(null)
let chartInstance = null

// 生成不同指标的模拟数据
const generateMetricData = (processName, testCase, metric) => {
  const processFactor = processName.toLowerCase().includes('kernel') ? 1.5 : 1.0
  const testCaseFactor = parseInt(testCase.id) % 5 * 0.1 + 1.0
  const randomFactor = (Math.random() - 0.5) * 0.2 // ±10%的随机波动

  switch (metric) {
    case 'rss':
      // RSS内存：50MB - 200MB
      const baseRss = 50000000 + Math.random() * 150000000
      return Math.floor(baseRss * processFactor * testCaseFactor * (1 + randomFactor))

    case 'pss':
      // PSS内存：通常比RSS小20-30%
      const basePss = 40000000 + Math.random() * 120000000
      return Math.floor(basePss * processFactor * testCaseFactor * (1 + randomFactor))

    case 'uss':
      // USS内存：通常比RSS小40-50%
      const baseUss = 30000000 + Math.random() * 100000000
      return Math.floor(baseUss * processFactor * testCaseFactor * (1 + randomFactor))

    case 'vsize':
      // 虚拟内存：通常很大，500MB - 2GB
      const baseVsize = 500000000 + Math.random() * 1500000000
      return Math.floor(baseVsize * processFactor * testCaseFactor * (1 + randomFactor))

    case 'swap':
      // 交换内存：0 - 50MB
      const baseSwap = Math.random() * 50000000
      return Math.floor(baseSwap * processFactor * testCaseFactor * (1 + randomFactor))

    case 'threads':
      // 线程数：1 - 50
      const baseThreads = 1 + Math.floor(Math.random() * 30)
      return Math.floor(baseThreads * processFactor * testCaseFactor * (1 + randomFactor))

    case 'priority':
      // 优先级：0 - 100
      const basePriority = Math.floor(Math.random() * 80)
      return Math.floor(basePriority * (1 + randomFactor))

    case 'vmmap_regions':
      // VMMap区域数：10 - 200
      const baseRegions = 10 + Math.floor(Math.random() * 150)
      return Math.floor(baseRegions * processFactor * testCaseFactor * (1 + randomFactor))

    default:
      return 0
  }
}

// 获取指标单位
const getMetricUnit = (metric) => {
  const memoryMetrics = ['rss', 'pss', 'uss', 'vsize', 'swap']
  return memoryMetrics.includes(metric) ? '内存占用' : metric
}

// 格式化指标值
const formatMetricValue = (value, metric) => {
  const memoryMetrics = ['rss', 'pss', 'uss', 'vsize', 'swap']
  if (memoryMetrics.includes(metric)) {
    return formatBytes(value)
  }
  return value.toString()
}

// 生成模拟数据
const generateProcessData = (existingTestCases) => {
  if (!props.processNames.length || !props.testCases.length || !props.metric.length) return []

  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#606266', '#FF6B6B', '#4ECDC4']
  const series = []

  // 获取实际进程在各测试用例中的存在情况
  const getProcessExistenceMap = (processName) => {
    const existence = {}
    existingTestCases.forEach(testCase => {
      // 检查该进程是否在该测试用例的进程列表中
      const exists = props.processData.some(process =>
        process.recordId === testCase.id &&
        process.processes.some(p => {
          const pBaseName = p.name.split('/').pop() || p.name
          const targetBaseName = processName.split('/').pop() || processName
          return pBaseName === targetBaseName
        })
      )
      existence[testCase.id] = exists
    })
    return existence
  }

  // 为每个进程和每个指标的组合生成系列
  props.processNames.forEach((processName, processIndex) => {
    const existenceMap = getProcessExistenceMap(processName)

    props.metric.forEach((metric, metricIndex) => {
      const colorIndex = (processIndex * props.metric.length + metricIndex) % colors.length
      const processColor = colors[colorIndex]

      // 只为该进程实际存在的测试用例生成数据点
      const data = existingTestCases
        .filter(testCase => existenceMap[testCase.id])
        .map(testCase => ({
          name: testCase.name,
          value: generateMetricData(processName, testCase, metric)
        }))

      // 如果进程不存在于任何测试用例中，跳过
      if (data.length === 0) return

      series.push({
        name: `${processName} (${getMetricLabel(metric)})`,
        type: 'line',
        data: data.map(item => item.value),
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
          color: processColor
        },
        itemStyle: {
          color: processColor,
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: processColor + '40' // 添加透明度
              },
              {
                offset: 1,
                color: processColor + '10'
              }
            ]
          }
        }
      })
    })
  })

  return series
}

// 获取指标标签
const getMetricLabel = (metric) => {
  const labels = {
    rss: 'RSS',
    pss: 'PSS',
    uss: 'USS',
    vsize: '虚拟内存',
    swap: '交换内存',
    threads: '线程数',
    priority: '优先级',
    vmmap_regions: 'VMMap区域'
  }
  return labels[metric] || metric
}

const initChart = () => {
  if (!chartRef.value || !props.processNames.length || !props.testCases.length) {
    showEmptyState()
    return
  }

  // 确保容器有正确的尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    setTimeout(() => {
      initChart()
    }, 100)
    return
  }

  // 如果已经存在实例，先销毁它
  if (chartInstance && !chartInstance.isDisposed()) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  // 获取所有选中进程存在的测试用例
  const getAllExistingTestCases = () => {
    const existingTestCaseIds = new Set()

    props.processNames.forEach(processName => {
      props.testCases.forEach(testCase => {
        const exists = props.processData.some(process =>
          process.recordId === testCase.id &&
          process.processes.some(p => {
            const pBaseName = p.name.split('/').pop() || p.name
            const targetBaseName = processName.split('/').pop() || processName
            return pBaseName === targetBaseName
          })
        )
        if (exists) {
          existingTestCaseIds.add(testCase.id)
        }
      })
    })

    return props.testCases.filter(testCase => existingTestCaseIds.has(testCase.id))
  }

  const existingTestCases = getAllExistingTestCases()
  const series = generateProcessData(existingTestCases)
  const categories = existingTestCases.map(testCase => testCase.name)

  // 获取主题配置
  const themeConfig = getChartThemeOptions()

  const option = {
    backgroundColor: themeConfig.backgroundColor,
    title: {
      text: '指定进程内存占用趋势对比',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: themeConfig.textColor
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        lineStyle: {
          color: '#999'
        }
      },
      backgroundColor: themeConfig.tooltip.backgroundColor,
      borderColor: themeConfig.tooltip.borderColor,
      textStyle: {
        color: themeConfig.tooltip.textStyle.color
      },
      formatter: (params) => {
        let html = `<div style="margin-bottom: 8px; font-weight: 600;">${params[0].axisValue}</div>`

        params.forEach(param => {
          const value = param.value
          // 从seriesName中提取指标类型（例如："kernel_task (RSS)" -> "rss"）
          const seriesName = param.seriesName
          const metricMatch = seriesName.match(/\(([^)]+)\)$/)
          const metricType = metricMatch ? metricMatch[1].toLowerCase() : props.metric[0]

          const formattedValue = formatMetricValue(value, metricType)
          html += `
            <div style="margin: 4px 0;">
              <span style="display: inline-block; width: 8px; height: 8px; background-color: ${param.color}; border-radius: 50%; margin-right: 8px;"></span>
              <span style="color: ${param.color}; font-weight: 600;">${seriesName}:</span>
              <span style="margin-left: 8px;">${formattedValue}</span>
            </div>
          `
        })

        return html
      }
    },
    legend: {
      textStyle: {
        color: themeConfig.textColor
      },
      top: 30,
      type: 'scroll'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%', // 增加底部空间以容纳倾斜的标签
      top: 80,
      containLabel: true,
      borderColor: themeConfig.grid.borderColor
    },
    xAxis: {
      type: 'category',
      data: categories,
      name: '测试用例',
      nameTextStyle: {
        color: themeConfig.textColor
      },
      axisLine: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisTick: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisLabel: {
        color: themeConfig.textColor,
        rotate: 45, // 文字倾斜45度以避免重叠
        interval: 0, // 显示所有标签
        fontSize: 12
      },
      splitLine: {
        lineStyle: {
          color: themeConfig.splitLineColor
        }
      }
    },
    yAxis: {
      type: 'value',
      name: getMetricUnit(props.metric),
      nameTextStyle: {
        color: themeConfig.textColor
      },
      axisLine: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisTick: {
        lineStyle: {
          color: themeConfig.axisColor
        }
      },
      axisLabel: {
        color: themeConfig.textColor,
        formatter: (value) => formatMetricValue(value, props.metric)
      },
      splitLine: {
        lineStyle: {
          color: themeConfig.splitLineColor
        }
      }
    },
    series: series
  }

  chartInstance.setOption(option)
}

const showEmptyState = () => {
  if (!chartRef.value) return

  // 如果已经存在实例，先销毁它
  if (chartInstance && !chartInstance.isDisposed()) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  const themeConfig = getChartThemeOptions()

  const option = {
    backgroundColor: themeConfig.backgroundColor,
    title: {
      text: '指定进程内存占用趋势对比',
      textStyle: {
        fontSize: 16,
        fontWeight: 600,
        color: themeConfig.textColor
      }
    },
    graphic: {
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: '请选择要分析的进程',
        fontSize: 16,
        fill: themeConfig.textColor,
        opacity: 0.7
      }
    }
  }

  chartInstance.setOption(option)
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance || chartInstance.isDisposed()) return
  initChart()
}

// 监听数据变化
watch(() => [props.processNames, props.testCases, props.metric], () => {
  updateChart()
}, { deep: true })

onMounted(() => {
  setTimeout(() => {
    // 使用 nextTick 确保 DOM 完全渲染
    nextTick(() => {
      initChart()
    })

    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    })

    // 监听主题变化
    themeObserver.value = watchThemeChange(() => {
      if (chartInstance && !chartInstance.isDisposed()) {
        // 重新初始化图表以应用新主题
        initChart()
      }
    })
  }, 500)
})

onUnmounted(() => {
  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }

  // 清理主题观察者
  if (themeObserver.value) {
    themeObserver.value.disconnect()
    themeObserver.value = null
  }

  // 清理事件监听器
  window.removeEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize()
    }
  })
})
</script>

<style scoped lang="scss">
.process-trend-chart {
  width: 100%;
  height: 100%;

  .chart {
    width: 100%;
    height: v-bind(height);
    min-height: 300px;
  }
}
</style>